<template> 
<div class="v-simple-cropper"> 
	<input class="file" ref="file" type="file" accept="image/*" @change="uploadChange"> 
	<div class="v-cropper-layer" ref="layer"> 
		<div class="layer-header">
			<van-row type="flex" justify="space-around">
			  <van-col span="6"><van-button type="default" @click="cancelHandle" size="large">取消</van-button></van-col>
			  <van-col span="6" offset="12"><van-button type="primary" @click="confirmHandle" size="large">确定</van-button></van-col>
			</van-row>
		</div> 
	  	<img ref="cropperImg"> 
	</div> 
</div> 
</template>
<script>
	import Cropper from 'cropperjs';
	import 'cropperjs/dist/cropper.min.css';

	import { Row, Col,Button } from 'vant';

	export default {
		name: 'v-simple-cropper',
		components: {
	        [Row.name] : Row,
	        [Col.name] : Col,
	        [Button.name] : Button,
	    },
		props: {
			initParam: Object,
			successCallback: {
				type: Function,
			}
		},
		data() {
			return {
				cropper: {},
			}
		},
		mounted() {
			this.init()
		},
		methods: {
			// 初始化裁剪插件 
			init() {
				let cropperImg = this.$refs['cropperImg']
				this.cropper = new Cropper(cropperImg, {
					aspectRatio: 1 / 1,
					dragMode: 'move'
				})
			},
			// 点击上传按钮 
			upload() {
				this.$refs['file'].click()
			},
			// 选择上传文件 
			uploadChange(e) {
				let file = e.target.files[0]
				this.filename = file['name']
				let URL = window.URL || window.webkitURL
				this.$refs['layer'].style.display = 'block'
				this.cropper.replace(URL.createObjectURL(file))
			},
			// 取消上传 
			cancelHandle() {
				this.cropper.reset()
				this.$refs['layer'].style.display = 'none'
				this.$refs['file'].value = ''
			},
			// 确定上传 
			confirmHandle() {
				let cropBox = this.cropper.getCropBoxData()
				let scale = this.initParam['scale'] || 1
				let cropCanvas = this.cropper.getCroppedCanvas({
					width: cropBox.width * scale,
					height: cropBox.height * scale
				})
				let imgData = cropCanvas.toDataURL('image/jpeg',0.5)
				this.successCallback(imgData);
				this.cancelHandle();
			}
		}
	}
</script>
<style lang="less"> 
.v-simple-cropper { 
	.file {display: none; }
	.v-cropper-layer {position: fixed; top: 0; bottom: 0; left: 0; right: 0; background: #fff; z-index: 99999; display: none;
		.layer-header {position: absolute; top: 5; left: 0; z-index: 99999; width: 100%; box-sizing: border-box; }
		img {position: inherit!important; border-radius: inherit!important; float: inherit!important; }
	} 
} 
</style> 